/*
 * @Author: tcosfish
 * @Date: 2022-08-03 15:14:18
 * @LastEditors: tcosfish
 * @LastEditTime: 2022-08-19 17:34:40
 * @FilePath: \loadFile\src\excel\RyExcel\index.ts
 */

import { Workbook, Worksheet } from "exceljs"
import xlsx from "xlsx"

import ry_database from "@/database/RyDataBase"

import { existsSync } from "fs"
import { tableTemplate } from "../utils/tableTemplate.util"
import { formatIndex } from "./formatIndex"
import { getVal } from "./getVal"

// * RyExcel 目前的作用
// *  1.读取 xlsx/xls/csv 文件 --- xlsx
// *  2. 根据数据+配置生成对应的 excel 文件 -- exceljs

class RyExcel {
  protected workbook: Workbook | null = null
  protected currentSht?: Worksheet
  constructor() {}
  readFile(filepath: string, initHeader: string[]) {
    let result: any[] = []
    if (existsSync(filepath.replace("xlsx", "xls"))) {
      console.log("文件已存在")
      console.log("正在查找文件对应缓存...")
      // result = RyCache.get(`${name}://${filename}`)
      console.log("已返回文件缓存")
    } else {
      console.log("文件不存在, 正在执行运行逻辑...")
      result = []
      const wb = xlsx.readFile(filepath)
      for (const sheet_name of wb.SheetNames) {
        const sheet = wb.Sheets[sheet_name]
        const sht = xlsx.utils.sheet_to_json(sheet, {
          header: initHeader,
          skipHidden: true,
        })
        let new_sht_data: any[] = []
        sht.forEach((row: any) => {
          if (row.id !== "ID") {
            let row_data: any = {}
            for (const key in row) {
              if (key !== "") {
                row_data[key] = row[key]
              }
            }
            new_sht_data.push(row_data)
          }
        })
        result.push(new_sht_data)
      }
      return result
    }
  }

  // 复制 Sheet
  async copy(filepath: string, copySheetName: string, id: number) {
    const budgetWb = new Workbook()
    await budgetWb.xlsx.readFile(filepath)
    const budget = budgetWb.getWorksheet(copySheetName)
    if (this.currentSht instanceof Object) {
      Object.assign(this.currentSht, budget, {
        name: this.currentSht.name,
        id: id,
        orderNo: id,
      })
    }
    return this
  }

  // 获取当前 Sheet
  getCurrentSht() {
    return this.currentSht
  }

  // 为复制过来的 Sheet填充数据
  async fill(indexCol: number, fillCol: number, dataSource: { entity: any }) {
    // 1. 获取索引行 indexCol
    const dobCol = this.currentSht?.getColumn(indexCol).values
    // 1.5 对索引行中数据进行处理
    const indexs = formatIndex(dobCol as string[])
    console.log(indexs)

    // 2. 使用索引行获取数据
    const connection = await ry_database.init()
    const result = await connection.getDataByIn(indexs, dataSource.entity)

    const v_1122 = getVal(result, "1122", "sum_debit")
    console.log(v_1122)

    // 3. 根据索引行, 将数据填充到指定行中
    this.currentSht?.eachRow((row) => {
      const index = row.getCell(indexCol).value
      if (typeof index === "string") {
        let value = ""
        if (index.indexOf(",") !== -1) {
          const indexs = index.split(",")
          value = indexs.reduce((p, c) => getVal(result, p) + getVal(result, c))
        } else {
          value =
            getVal(result, index, "sum_debit") ||
            getVal(result, index, "sum_credit")
        }
        if (value) row.getCell(fillCol).value = value
      }
    })
  }

  // 创建工作簿文件, 设置基本信息
  createTemplate() {
    this.workbook = new Workbook()
    this.workbook.creator = "tcosfish" // 创建者
    this.workbook.modified = new Date() // 修改日期
    this.workbook.properties.date1904 = true // 将工作簿时期设置为1994年系统
    this.workbook.calcProperties.fullCalcOnLoad = true // 在加载时强制计算工作簿属性
    return this
  }

  // 新增一个 sheet表
  addSheet(sheetName: string, tableOption?: any) {
    const sht = this.workbook?.addWorksheet(sheetName, {
      properties: { defaultColWidth: 40, defaultRowHeight: 20 },
      pageSetup: {
        showGridLines: true,
        horizontalCentered: true,
        verticalCentered: true,
      },
    })
    this.currentSht = sht
    return this
  }

  // 在之前的 sheet表中新增一个 table表块
  addTable(
    table_name: string,
    start_line: string,
    fields: any[],
    data: any[],
    mode?: "create" | "fill"
  ) {
    this.currentSht?.addTable(
      tableTemplate(table_name, start_line, fields, data)
    )
    return this
  }

  // 将文件保存到指定路径
  async saveFile(save_filepath: string) {
    await this.workbook?.xlsx.writeFile(save_filepath)
    console.log(`文件已保存到 ${save_filepath}`)
  }
}

export default new RyExcel()
